<?php
/**
 * 微信公众号推送
 * @App	
 * @Group 
 * @Action WeChatPushAction
 * @author lilei
 * @date 2018年8月23日
 *
 */
namespace app\crontab\controller\wechat;

use app\common\model\ExchangeModel;
use app\common\model\wechat\WeChatExchangeModel;
use app\common\model\wechat\WeChatPushArticleModel;
use app\common\model\wechat\WeChatUserCoinModel;
use app\common\model\wechat\WeChatUserModel;
use app\common\redis\WeChatPushArticleRepeatRedis;
use app\common\service\PidFile;
use app\common\service\wechat\WeChatTemplateMsg;
use app\crontab\controller\CrontabCommon;

class Push extends CrontabCommon {

	/**
	 * 推送文章
	 */
	public function pushArticle() {
		if (!PidFile::createPidFile('pushArticle', 1)) {
			echo '进程已启动足够数量' . PHP_EOL;
			return;
		}
		// 公众号文章推送表
		$WeChatPushArticleModel = new WeChatPushArticleModel();
        $WeChatUserCoinModel = new WeChatUserCoinModel();
		$WeChatUserModel     = new WeChatUserModel();
		//用户关注交易所 18.11.13 @thinkphper
		$exmodel       =  new WeChatExchangeModel();
		$model         =  new ExchangeModel();
		// 推送列表
		$pushList = array();
		// 获取需要推送的文章列表
		$pushArticleList  = $WeChatPushArticleModel->getPushList();
        $redisModel = WeChatPushArticleRepeatRedis::getInstance();
		foreach ( $pushArticleList as $data ) {
		    if ( $data['coin_id'] >0 ){
                $userOpenIdList = $WeChatUserCoinModel->getCoinPushWechatUserOpenIdList($data['coin_id']);
            } elseif($data['coin_id'] ==-1){
                $followids = $WeChatUserCoinModel->getFollowOpenids();
                $ids       = $WeChatUserModel->getWechatUids();
                $userOpenIdList = array_values(array_diff($ids, $followids));
            } elseif ($data['coin_id'] ==-2) {
            	$userOpenIdList = $exmodel->getExchangePushList($data['exchange_id']);
            } else {
                $userOpenIdList = $WeChatUserCoinModel->getAllPushWechatUserOpenIdList( );
            }
 
			if ( $userOpenIdList ) {
				foreach ( $userOpenIdList as $openid ) {
				    // 增加文章推送缓存
                    if ( $redisModel->getRepeatStr( $openid, $data['article_id']) ){
                        // 检测3分钟内有推送
                        continue;
                    }

                    $redisModel->setRepeatStr( $openid, $data['article_id']);
					$data['open_id'] = $openid;
					$pushList[] = $data;
				}
			}
			// 更新状态为已推送
			$update = array(
					'is_push' => 1,
			);
			$WeChatPushArticleModel->update_data($data['id'], $update);
		}
		
		if ( $pushList ) {
			// 计算总数量
			$total = count($pushList);
			// 10 个进程
			$process = 10;
			// 每个进程数据数量
			$limit = ceil($total/$process);
			// 数据切割分组
			$all_data_chunk = array_chunk($pushList, $limit);
			// 主进程池
			$pid_list = array();
			// 多进程处理
			foreach ( $all_data_chunk as $kp=>$vp ) {
				$pid = pcntl_fork();
				if( $pid==-1 ){
					die("can not fork");
				}elseif ( $pid ) {
					$pid_list[] = $pid;
				}else {
					// 执行代码
					$wxTemplateMsgService = new WeChatTemplateMsg();
					foreach ( $vp as $data ) {
						try {
                            if ($data['coin_id'] ==-1) {
                                $project  = "\r\nHOLD的核心服务是基于用户关注的币种，为您推送币种资讯提醒和价格异动提醒。回复币种名称（如 BTC），您会第一时间收到提醒";
                            }elseif($data['coin_id'] ==-2){
                            	$list = $model->where(['id'=>$data['exchange_id']])->find();
                            	$data['symbol'] = $list['name']."交易所";
                            	$project  = "\r\n点击查看全文 ↓";
                            }else{
                                $project  = "\r\n点击查看全文 ↓";
                            }
							$wxTemplateMsgService->sendTemplateMsg($data['open_id'], $data['url'], $data['title'], $data['symbol'], $data['remark'], $project);
						}catch ( \Exception $e ) {
							echo $e->getCode().PHP_EOL;
							echo $e->getMessage().PHP_EOL;
						}
					}
					exit();
				}
			}// End chunk foreach
			while(count($pid_list) > 0)
			{
				$myId = pcntl_waitpid(-1, $status, WNOHANG);
				foreach($pid_list as $key => $pid)
				{
					if($myId == $pid) unset($pid_list[$key]);
				}
			}
		} // End IF
	}
	
}